package com.yej.aiPolice.ui.activity

import android.Manifest
import android.annotation.SuppressLint
import android.app.Activity
import android.content.ContentValues
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.*
import android.provider.MediaStore
import android.util.Log
import android.view.View
import android.widget.Button
import android.widget.ImageView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.core.content.FileProvider
import androidx.core.os.EnvironmentCompat
import com.yej.aiPolice.R
import com.yej.aiPolice.model.beans.UserFaceInfoBean
import com.yej.aiPolice.presenter.PicActivityPresenter
import com.yej.aiPolice.util.AiPoliceAPP
import com.yej.aiPolice.util.IOUtil
import com.yej.aiPolice.util.UriUtil
import kotlinx.android.synthetic.main.activity_search_info.*
import java.io.File
import java.io.IOException
import java.text.SimpleDateFormat
import java.util.*

class PicActivity : AppCompatActivity() {

    private var ivPhoto: ImageView? = null
    private var picActivityPresenter =  PicActivityPresenter(this)
    /**
     * 用于保存拍照图片的uri
     */
    private var mCameraUri: Uri? = null
    /**
     * 用于保存图片的文件路径，Android 10以下使用图片路径访问图片
     */
    private var mCameraImagePath: String? = null
    /**
     * 是否是Android 10以上手机
     */
    private val isAndroidQ = Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_search_info)
        val btCamera =
            findViewById<Button>(R.id.btn_photo)
        val emgCall = findViewById<Button>(R.id.btn_call_emg_tel)
        ivPhoto = findViewById(R.id.iv_search_face)

//        Log.e("创建","调用")
//        tv_user_name.text = "我可以改她"
        btCamera.setOnClickListener(View.OnClickListener { checkPermissionAndCamera() })
        emgCall.setOnClickListener {
            var intent = Intent()
            intent.action = Intent.ACTION_DIAL//dial是拨号的意思
            intent.data = Uri.parse("tel:18060969530")//这个tel不能改，后面的数字可以随便改
            startActivity(intent)

            var intent2 = Intent()
            intent.action = Intent.ACTION_SENDTO//发短信的action
            intent.data = Uri.parse("smsto:18060969530")//smsto:后面的是收信人，可以随便改
            intent.putExtra("sms_body", "我叫"+AiPoliceAPP.sUser.realname+"我这里有紧急情况，不方便拨打电话，我的住址是"+AiPoliceAPP.sUser.dfAddress+"我的紧急联系人电话为"+AiPoliceAPP.sUser.emgContactNum)//这里的第二个参数是短信内容
            startActivity(intent)
        }
    }

    /**
     * 检查权限并拍照。
     * 调用相机前先检查权限。
     */
    private fun checkPermissionAndCamera() {
        val hasCameraPermission = ContextCompat.checkSelfPermission(
            application,
            Manifest.permission.CAMERA
        )
        if (hasCameraPermission == PackageManager.PERMISSION_GRANTED) { //有权限，调起相机拍照。
            openCamera()
        } else { //没有权限，申请权限。
            ActivityCompat.requestPermissions(
                this, arrayOf(Manifest.permission.CAMERA),
                PERMISSION_CAMERA_REQUEST_CODE
            )
            ActivityCompat.requestPermissions(
                this, arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE),
                PERMISSION_CAMERA_REQUEST_CODE
            )
        }
    }

    override fun onActivityResult(
        requestCode: Int,
        resultCode: Int,
        data: Intent?
    ) {
        super.onActivityResult(requestCode, resultCode, data)
        println("==================resultCode = $resultCode")
        if (requestCode == CAMERA_REQUEST_CODE) {
            if (resultCode == Activity.RESULT_OK) {
                println(mCameraUri)
                ivPhoto!!.setImageURI(mCameraUri)

                val path = UriUtil.getFilePathFromURI(this, mCameraUri)
                var file:File =  File(path);
                var bitMap = IOUtil.readBitmapFromFileDescriptor(path, 200, 200)
                ivPhoto?.setImageBitmap(bitMap)

                Log.e("人脸",path)
                picActivityPresenter!!.searchFace(path)
            } else {
                Toast.makeText(this, "取消", Toast.LENGTH_LONG).show()
            }
        }
    }

    /**
     * 处理权限申请的回调。
     *
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<String>,
        grantResults: IntArray
    ) {
        if (requestCode == PERMISSION_CAMERA_REQUEST_CODE) {
            if (grantResults.size > 0
                && grantResults[0] == PackageManager.PERMISSION_GRANTED
            ) { //允许权限，有调起相机拍照。
                openCamera()
            } else { //拒绝权限，弹出提示框。
                Toast.makeText(this, "拍照权限被拒绝", Toast.LENGTH_LONG).show()
            }
        }
    }

    /**
     * 调起相机拍照
     */
    private fun openCamera() {
        val captureIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
        // 判断是否有相机
        if (captureIntent.resolveActivity(packageManager) != null) {
            var photoFile: File? = null
            var photoUri: Uri? = null
            if (isAndroidQ) { // 适配android 10
                photoUri = createImageUri()
            } else {
                try {
                    photoFile = createImageFile()
                } catch (e: IOException) {
                    e.printStackTrace()
                }
                if (photoFile != null) {
                    mCameraImagePath = photoFile.absolutePath
                    println("path = $mCameraImagePath")
                    photoUri =
                        if ( /*Build.VERSION.SDK_INT >= Build.VERSION_CODES.N*/true) { //7.0到9.0
                            //适配Android 7.0文件权限，通过FileProvider创建一个content类型的Uri 如：content://
                            FileProvider.getUriForFile(
                                this@PicActivity,
                                "com.donkingliang.photograph.fileprovider", photoFile
                            )
                        } else { //7.0以下, 如：file://
                            Uri.fromFile(photoFile)
                        }
                }
            }
            println("photoUri = $photoUri")
            mCameraUri = photoUri
            if (photoUri != null) {
                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
                    val resInfoList = packageManager
                        .queryIntentActivities(captureIntent, PackageManager.MATCH_DEFAULT_ONLY)
                    for (resolveInfo in resInfoList) {
                        val packageName = resolveInfo.activityInfo.packageName
                        grantUriPermission(
                            packageName, photoUri,
                            Intent.FLAG_GRANT_WRITE_URI_PERMISSION or Intent.FLAG_GRANT_READ_URI_PERMISSION
                        )
                    }
                }
                captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri)
                captureIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
                startActivityForResult(
                    captureIntent,
                    CAMERA_REQUEST_CODE
                )
            }
        }
    }

    /**
     * 创建图片地址uri,用于保存拍照后的照片 Android 10以后使用这种方法
     * @return 图片的uri
     */
    private fun createImageUri(): Uri? { //设置保存参数到ContentValues中
        val contentValues = ContentValues()
        //设置文件名
        contentValues.put(
            MediaStore.Images.Media.DISPLAY_NAME,
            System.currentTimeMillis().toString() + ""
        )
        //兼容Android Q和以下版本
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { //android Q中不再使用DATA字段，而用RELATIVE_PATH代替
//TODO RELATIVE_PATH是相对路径不是绝对路径;照片存储的地方为：内部存储/Pictures/preventpro
            contentValues.put(MediaStore.Images.Media.RELATIVE_PATH, "Pictures/preventpro")
        }
        //设置文件类型
        contentValues.put(MediaStore.Images.Media.MIME_TYPE, "image/JPEG")
        //执行insert操作，向系统文件夹中添加文件
//EXTERNAL_CONTENT_URI代表外部存储器，该值不变
        return contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues)
    }

    /**
     * 创建保存图片的文件
     * @return
     * @throws IOException
     */
    @Throws(IOException::class)
    private fun createImageFile(): File? {
        val imageName = SimpleDateFormat(
            "yyyyMMdd_HHmmss",
            Locale.getDefault()
        ).format(Date()) + ".jpg"
        //        File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
//        File storageDir = Environment.getExternalStoragePublicDirectory(
//                Environment.DIRECTORY_PICTURES);
        val storageDir = File(
            Environment.getExternalStorageDirectory().absolutePath
                    + File.separator + "Pictures" + File.separator + "abc"
        )
        if (!storageDir.exists()) storageDir.mkdirs()
        val tempFile = File(storageDir, imageName)
        return if (Environment.MEDIA_MOUNTED != EnvironmentCompat.getStorageState(tempFile)) {
            null
        } else tempFile
    }


    fun onSearchSuccess() {
        Thread(UpUpdateInfo()).start()
    }

    fun onSearchFail() {
        TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
    }

    val handler = @SuppressLint("HandlerLeak")
    object : Handler(){
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            if(msg!!.what == 1){
                val userFaceInfoBean:UserFaceInfoBean = AiPoliceAPP.sFaceInfo;
                tv_user_name.text = userFaceInfoBean.name
                tv_user_tel.text = userFaceInfoBean.tel
                tv_user_address.text = userFaceInfoBean.address
                tv_user_emg_name.text = userFaceInfoBean.emgContactName
                tv_user_emg_tel.text = userFaceInfoBean.emgContactNum
                tv_user_crime.text = userFaceInfoBean.criminalRecord
                changeState(userFaceInfoBean.state)
            }

        }
    }

    @SuppressLint("ResourceAsColor")
    fun changeState(state:String){
        when(state){
            "0" ->{
                tv_user_state.text = "普通公民"
                tv_user_state.setTextColor(R.color.green1);
            }

            "1" -> {
                tv_user_state.text = "走失人口"
                tv_user_state.setTextColor(R.color.blue0);
            }
            "2" -> {
                tv_user_state.text = "逃犯"
                tv_user_state.setTextColor(R.color.red0);
            };

        }
    }



    inner class UpUpdateInfo :Runnable{
        override fun run() {
                handler.sendEmptyMessage(1)
        }

    }

    companion object {
        // 拍照的requestCode
        private const val CAMERA_REQUEST_CODE = 0x00000010
        // 申请相机权限的requestCode
        private const val PERMISSION_CAMERA_REQUEST_CODE = 0x00000012
    }
}